package cn.aixuegao.mybatis.factory;

import cn.aixuegao.common.bean.Rule;
import cn.aixuegao.common.enums.OperateEnum;
import net.sf.jsqlparser.expression.BinaryExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.expression.operators.relational.*;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: huangxingyao
 * @date: 2020/03/31
 * @what:
 * @why:
 * @how:
 */
public class ExpressionFactory {

    public static Expression perfect(OperateEnum operate, Column column, String value) {

        if (OperateEnum.IN == operate) {
            return perfectInExpression(column, value);
        }

        BinaryExpression binaryExpression;
        switch (operate) {
            case MINOR:
                binaryExpression = new MinorThan();
                break;
            case GREATER:
                binaryExpression = new GreaterThan();
                break;
            case MINOR_EQ:
                binaryExpression = new MinorThanEquals();
                break;
            case GREATER_EQ:
                binaryExpression = new GreaterThanEquals();
                break;
            case LIKE:
                binaryExpression = new LikeExpression();
                break;
            default:
                binaryExpression = new EqualsTo();
                break;
        }
        binaryExpression.setLeftExpression(column);
        binaryExpression.setRightExpression(new StringValue(value));
        return binaryExpression;
    }

    /**
     * 构建 InExpression 表达式
     * @param column
     * @param value
     * @return
     */
    private static Expression perfectInExpression(Column column, String value) {
        InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(column);

        String[] valueArr = StringUtils.split(value, ",");

        List<Expression> expressions = new ArrayList();
        for (String val : valueArr) {
            expressions.add(new StringValue(val));
        }
        inExpression.setRightItemsList(new ExpressionList(expressions));
        return inExpression;
    }




}
